function [beta,resid,sigma,G]=ols_ar(yd,nlag,flag_c); 
% ================================================== 
% OLS_AR.M 
% function [beta,resid,sigma,G]=ols_ar(yd,nlag,flag_c,); 
% 
% OLS when yd is univariate 
% NLAG is lag dimension 
% FLAG_C == 0  No constant 
%        === 1 Mean 
% 
% Output 
% ======
% BETA      Row vector 
%           if a constant is added it is the last element 
% RESID     matrix of residuals 
% SIGMA     standard deviation residuals 
% G         Provided only if function called with 4 output arguments 
%           Companion form matrix 
%           If constant is estimated, not included 
% 
% Alejandro Justiniano  (C) Feb 11 2006 
% ===================================================
yd = yd(:); 
t  = length( yd ); 
xd = lagmat( yd(:) , nlag ); 
if flag_c == 1 
    xd = [xd ones(t,1) ]; 
end 
yd = xd(nlag+1:end,1); 
xd = xd(nlag+1:end,2:end); 

k = size( xd , 2 ); 
q=(xd'*xd);
q=q\eye(k);
beta=q*xd'*yd;
resid=yd-xd*beta;
sigma=std(resid);
beta=beta';

if nargout == 3 
    return 
else 
    if nlag == 1; 
        G = beta(1); 
    else 
        G = zeros( nlag );     
        G(2:end,1:nlag-1) = eye( nlag-1); 
        if flag_c == 1
            G(1,:) = beta(1:end-1); 
        else 
            G(1,:) = beta ; 
        end 
    end 
end 

    
